import api from '@/store/api';
import i18n from '@/i18n';
const { t } = i18n.global as any;

export const usePoliciesStore = defineStore('policies', () => {
  const sshProtocolEnabled = ref(false);
  const ipmiProtocolEnabled = ref(false);

  const setSshProtocolEnabled = (enabled: any) =>
    (sshProtocolEnabled.value = enabled);
  const setIpmiProtocolEnabled = (enabled: any) =>
    (ipmiProtocolEnabled.value = enabled);

  const getNetworkProtocolStatus = async () => {
    return await api
      .get('/redfish/v1/Managers/bmc/NetworkProtocol')
      .then((response) => {
        const sshProtocol = response.data.SSH.ProtocolEnabled;
        const ipmiProtocol = response.data.IPMI.ProtocolEnabled;
        setSshProtocolEnabled(sshProtocol);
        setIpmiProtocolEnabled(ipmiProtocol);
      })
      .catch((error) => console.log(error));
  };
  const saveIpmiProtocolState = async (protocolEnabled: any) => {
    setIpmiProtocolEnabled(protocolEnabled);
    const ipmi = {
      IPMI: {
        ProtocolEnabled: protocolEnabled,
      },
    };
    return await api
      .patch('/redfish/v1/Managers/bmc/NetworkProtocol', ipmi)
      .then(() => {
        if (protocolEnabled) {
          return t('pagePolicies.toast.successIpmiEnabled');
        } else {
          return t('pagePolicies.toast.successIpmiDisabled');
        }
      })
      .catch(() => {
        setIpmiProtocolEnabled(!protocolEnabled);
        if (protocolEnabled) {
          throw new Error(t('pagePolicies.toast.errorIpmiEnabled') as string);
        } else {
          throw new Error(t('pagePolicies.toast.errorIpmiDisabled') as string);
        }
      });
  };
  const saveSshProtocolState = async (protocolEnabled: any) => {
    setSshProtocolEnabled(protocolEnabled);
    const ssh = {
      SSH: {
        ProtocolEnabled: protocolEnabled,
      },
    };
    return await api
      .patch('/redfish/v1/Managers/bmc/NetworkProtocol', ssh)
      .then(() => {
        if (protocolEnabled) {
          return t('pagePolicies.toast.successSshEnabled');
        } else {
          return t('pagePolicies.toast.successSshDisabled');
        }
      })
      .catch((error) => {
        console.log(error);
        setSshProtocolEnabled(!protocolEnabled);
        if (protocolEnabled) {
          throw new Error(t('pagePolicies.toast.errorSshEnabled') as string);
        } else {
          throw new Error(t('pagePolicies.toast.errorSshDisabled') as string);
        }
      });
  };

  return {
    sshProtocolEnabled,
    ipmiProtocolEnabled,
    setSshProtocolEnabled,
    setIpmiProtocolEnabled,
    getNetworkProtocolStatus,
    saveIpmiProtocolState,
    saveSshProtocolState,
  };
});
